package com.qf.controller;
import com.qf.enums.ExceptionEnums;
import com.qf.enums.PageEnum;
import com.qf.exception.ExamException;
import com.qf.vo.ResultVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.tools.Diagnostic;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadController {
private final long MAX_SIZE=5243880;
@Value("${pic.types}")
private String types;
@Value("${pic.path}")
private String path;
@RequestMapping("/pic")
public ResultVo pic(MultipartFile file){
//首先校验图片不能为空
if(file==null){
    log.info("图片不能为空");
    throw new ExamException(ExceptionEnums.PIC_NULL);
}
//校验大小
    if(file.getSize()>MAX_SIZE){
        log.info("图片过大了");
        throw new ExamException(ExceptionEnums.PICFILE_BIG);
    }
    //校验类别
    boolean falg=false;
    for (String type : types.split(",")) {
        if(StringUtils.endsWithIgnoreCase(file.getOriginalFilename(),type)){
            falg=true;
            break;
        }
    }
    if(!falg){
        log.info("【图片类型不匹配】,file={}",file);
        throw new ExamException(ExceptionEnums.PICFILE_TYPE);
    }
    //判断是否损坏
    BufferedImage read = null;
    try {
        read = ImageIO.read(file.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    if(read==null){
        log.info("【图片已经损坏】图片已损坏");
        throw new ExamException(ExceptionEnums.BAD);
    }
    //起一个新的名字
    String prefixname= UUID.randomUUID().toString();
    String suffixname=file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
    String newName=prefixname+suffixname;
    //指定保存图片的本地路径
    File pathFile=new File(path+newName);
    System.out.println(path);
   if (!pathFile.getParentFile().exists()){
        pathFile.getParentFile().mkdirs();
    }

    try {
        file.transferTo(pathFile);
    } catch (IOException e) {
        e.printStackTrace();
    }
    //静态资源路径,将path:D:/poor/pic/指定为静态资源路径
    String url="http://localhost/pic/" + newName;
    return new ResultVo(0,"",url);
}
}
